package com.ericsson.mna.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ericsson.mna.model.bs.UserRegisterServices;
import com.ericsson.mna.model.pojo.DBConf;
import com.ericsson.mna.model.pojo.TodoUser;

/**
 * Servlet implementation class LoginController
 */
@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userId=request.getParameter("signum");
		String password=request.getParameter("password");
		//String role=request.getParameter("role");
		String role="1";
		PrintWriter out=response.getWriter();
		TodoUser tu=new TodoUser();
		tu.setUserId(userId);
		tu.setPassword(password);
		tu.setRole(role);
		System.out.println("user data:::"+ tu);
		HttpSession session=null;
		Properties prop=new Properties();
		prop.load(getServletContext().getResourceAsStream("/view/resources/prop/DbConf.properties"));
		DBConf dbconf=new DBConf();
		dbconf.setDriverName(prop.getProperty("driverName"));
		dbconf.setPassword(prop.getProperty("password"));
		dbconf.setUrl(prop.getProperty("url"));
		dbconf.setUserName(prop.getProperty("userName"));
		System.out.println("Testing Properties file values:::"+dbconf);
		if((UserRegisterServices.checkUser(tu,dbconf)))
		{
			session=request.getSession(true);
			session.setAttribute("userId",userId);
			session.setAttribute("role",role);
			RequestDispatcher rd=request.getRequestDispatcher("tab.jsp");
			rd.forward(request,response);
		//	response.sendRedirect("homepage.jsp");
		}
		else
		{
			out.println("<script language=javascript>");
			out.println("<!--");
			out.println("alert('Error:Wrong userId or password');");
			out.print("window.location='login.jsp'");
			out.println("//-->");
			out.println("</script>");
			//response.sendRedirect("homepage.jsp");
		}





	}

}
